# encoding=utf-8

import androidhelper, sqlite3, sys

reload(sys)
sys.setdefaultencoding('utf8')

droid = androidhelper.Android()
cx = sqlite3.connect("/sdcard/weixiu.db")

fs = ['person', 'phone', 'product', 'date0', 'status', 'remark']
fs1 = ['姓名', '电话', '产品', '日期', '状态', '备注']

cu = cx.cursor()
cu.execute('CREATE TABLE IF NOT EXISTS weixiu(%s)' % ','.join(map(lambda i: i + ' VARCHAR(20)', fs)))


def choose(title, ls):
    droid.dialogCreateAlert(title, '')
    droid.dialogSetItems(ls)
    droid.dialogShow()
    return droid.dialogGetResponse().result[u'item']


def prompt(message):
    return droid.dialogGetInput('请输入', message, '').result.encode('utf-8')


def execute(sql, action):
    print sql
    cu.execute(sql)
    cx.commit()
    droid.makeToast(action + '成功')


if choose('请选择操作', ['查询', '新建']):
    execute("INSERT INTO weixiu VALUES('%s')" % "','".join(map(lambda i: prompt(i), fs1)), '新建')
else:
    sql = "SELECT * FROM weixiu WHERE %s LIKE '%%%s%%'" % (fs[choose('请选择查询字段', fs1)], prompt('查询内容'))
    print sql
    cu.execute(sql)
    r = cu.fetchall()
    droid.dialogCreateAlert('', r and '\n\n'.join(
        map(lambda i: '\n'.join(map(lambda j: fs1[j] + ':' + i[j], range(len(i)))), r)) or '找不到')
    droid.dialogShow()
